<template>
  <div class="cart-page">
    <div class="cart-list-page">
      <div class="list-box">
        <el-table
            :data="pageList"
            :header-cell-style="{ 'backgroundColor': 'rgb(246, 246, 246)'}"
            row-key="id"
            height="100%"
            style="width: 100%"
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"/>
          <el-table-column label="意向模特">
            <template #default="scope">
              <div class="img-box">
                <el-image :src="scope.row.goods.cover_pic" style="border-radius: 4px;"></el-image>
                <div style="padding-left: 10px">{{ scope.row.goods.name }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价（每条）" width="120" align="right">
            <template #default="scope">
              {{ scope.row.goods.price }} $
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center" width="220">
            <template #default="scope">
              <el-input-number v-model="scope.row.num" @change="setOrderTotal" :min="1"/>
            </template>
          </el-table-column>
          <el-table-column label="金额" width="120" align="right">
            <template #default="scope">
              {{ Number(scope.row.goods.price * scope.row.num).toFixed(2) }} $
            </template>
          </el-table-column>
          <el-table-column label="下单时间" width="180" align="center">
            <template #default="scope">
              {{ scope.row.goods.created_at }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button size="small" @click="removeItem(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--<div class="cart-item" v-for="(item, index) in pageList" :key="'mch_'+ index">-->
        <!--  {{ item }}-->
        <!--</div>-->

        <!--{{ pageList}}-->
      </div>

      <div class="pay-box">
        <div style="flex: 1">
          套餐剩余数量：<span style="font-size: 26px">{{userIntegral}} </span> 条
        </div>

        <div>
          <div class="pay-box-top">
            <div class="bto-title">
              已选数量：
              <span style="color: #d67c5a;display: inline-block;text-align: center"> {{ totalNum }} </span>
              ，当前预估总计
              <span style="font-size: 25px;color: #d67c5a;"> {{ totalMoney }} </span>
              <span style="color: #d67c5a;"> USD</span>

            </div>
          </div>
          <div>*此处价格展示为美金价格，最终结算价格请以结算页为准。</div>
        </div>
        <template v-if="totalNum==0">
          <el-button disabled class="cart-pay-btn" type="primary">立即支付</el-button>
          <el-button disabled class="cart-pay-btn" type="warning">套餐支付</el-button>
        </template>
        <template v-else>
          <el-button @click="orderPreview(1)" class="cart-pay-btn" type="primary">立即支付</el-button>
          <el-button @click="orderPreview(0)" class="cart-pay-btn" type="warning">套餐支付</el-button>
        </template>



      </div>
    </div>

  </div>
</template>
<script setup lang="ts">
import Https from "@/server";
import {onMounted} from "vue";
import {ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {useRouter} from "vue-router";

const router = useRouter();

interface User {
  id: number
  num: number
}

const totalNum = ref(0);
const totalMoney = ref("0.00");
const userIntegral = ref(0);
const selectOrder = ref<User[]>([]);

const pageList = ref<User[]>([]);
const handleSelectionChange = (val: User[]) => {
  selectOrder.value = val;
  totalNum.value = 0;
  totalMoney.value = "0.00";
  val.forEach((item: any) => {
    totalNum.value += Number(item.num);
    totalMoney.value = (Number(item.num) * Number(item.goods.price) + Number(totalMoney.value)).toFixed(2).toString();
  })
  // totalNum
}

const getPageList = async () => {
  await Https.getCartList().then((res: any) => {
    if (res.code == 0) {
      if (res.data.list.length > 0) {
        pageList.value = res.data.list[0].goods_list;
      }
    } else {
      ElMessage.error(res.msg);
    }
  })
}

const setOrderTotal = () => {
  handleSelectionChange(selectOrder.value)
}


const orderPreview = (type:number) => {
  sessionStorage.setItem("orderData", JSON.stringify(selectOrder.value))
  // sessionStorage.setItem("orderPayType", type.toString())
  if(type == 1 && totalNum.value>userIntegral.value){
    ElMessage.warning("余额不足")
    return false
  }
  router.push({name: "create",query:{payType: type}});
}


const removeItem = (row: { id: number, mch_id: number }) => {
  ElMessageBox.confirm(
      "确认这位模特移出购物车？",
      "请确认",{
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true,
      }
  ).then(() => {
    let cart_id_list = [
      {mch_id: row.mch_id, id: row.id},
    ]
    let data = {
      cart_id_list: JSON.stringify(cart_id_list),
    }

    Https.postDeleteCart(data).then((res: any) => {
      if (res.code == 0) {
        ElMessage.success("已将此模特移出");
        getPageList();
      } else {
        ElMessage.error(res.msg);
      }
    })

  }).catch(() => {
    console.log("已取消")
  })
}

// 用户套餐余额
const userWallet = () => {
  Https.getWebConfig({}).then((res: any) => {
    if (res.code === 0) {
      userIntegral.value = res.data.user_info.options.integral ? res.data.user_info.options.integral : "暂无余额"
    }
  })
}

onMounted(() => {
  getPageList();
  userWallet();
})

</script>
<style scoped lang="scss">
.cart-page {
  width: 100%;
  box-sizing: border-box;
  padding-right: 8px;
  overflow: hidden;

  .cart-list-page {
    background-color: #fff;
    padding: 25px 10px 10px;
    border-radius: 14px;
  }
}

.list-box {
  width: 100%;

  display: flex;
  overflow: auto;
  height: calc(100vh - 260px);
  flex-wrap: wrap;
  position: relative;

  .img-box {
    display: flex;
    align-items: center;

    .el-image {
      width: 50px;
    }
  }
}

.pay-box {
  height: 70px;
  padding: 10px 10px 0;
  box-sizing: border-box;
  border-top: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.pay-box-top {
  padding-right: 20px;
  display: flex;
  justify-content: flex-end;

  .bto-title {
    color: #09172f;
  }
}

.cart-pay-btn {
  width: 140px;
  height: 44px;
  margin-left: 20px;
  border-radius: 22px;
}

</style>